<template>
  <div class="uploader">
    <input
      type="file"
      style="display:none"
      ref="upload"
      @change="fileChange"
    />
    <div
      class="am-btn am-btn-default am-btn-success"
      @click="btnClick"
    >
      {{btnText}}
    </div>
  </div>
</template>
<script>
import io from '../../lib/io'
export default {
  data() {
    return {}
  },
  props: {
    uploadType: {
      type: String,
      default: 'picture'
    },
    uploadData: {
      type: Object,
      default: () => {
        return null
      }
    },
    uploadField: {
      type: String,
      default: ''
    },
    apiUrl: {
      type: String,
      default: ''
    },
    btnText: {
      type: String,
      default: '上传'
    },
    acceptType: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  mounted() {
    this.upload = this.$refs.upload
  },
  methods: {
    btnClick() {
      this.upload.click()
    },
    fileChange() {
      let uploadFile = this.upload.files[0]
      let ext = uploadFile.name.replace(/.*(?=\.)\./g, '')
      const isValidExt = this.acceptType.some(extItem => {
        return extItem === ext
      })
      if (!isValidExt) {
        this.$alert(
          `文件格式错误，只允许上传${this.acceptType.join('、')}等格式的文件`
        )
        return
      }
      let reader = new FileReader()
      let formData = new FormData()
      formData.append(this.uploadField, this.upload.files[0])
      if (this.uploadData) {
        Object.keys(this.uploadData).forEach(key => {
          formData.append(key, this.uploadData[key])
        })
      }
      reader.readAsDataURL(uploadFile)
      reader.onload = e => {
        if (this.uploadType === 'file') {
          this.$showLoading()
          io.postMitiFile(this.apiUrl, formData, ret => {
            this.$hiddenLoading()
            this.upload.value = ''
            if (ret.ok && ret.data.success) {
              this.$alert('导入成功')
            } else {
              this.$alert(ret.data.desc || '上传失败')
            }
          })
        } else if (this.uploadType === 'picture') {
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.uploader {
  display: inline-block;
}
</style>
